package com.wenbing.miio.core;

import com.wenbing.miio.core.exception.NetworkLayerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 线程
 * @author wen bing
 * @projectName: miio
 * @package: com.wenbing.miio.core
 * @className: DaemonThread
 * @date 2024/09/22 10:36
 **/
public class InnerThread extends Thread  {
    private static final Logger LOGGER = LoggerFactory.getLogger(InnerThread.class);

    @FunctionalInterface
    public interface Runnable {
        void run() throws IOException, NetworkLayerException, InterruptedException;
    }

    private static class DaemonThread extends InnerThread {
        public DaemonThread(String name, Runnable runnable) {
            super("daemon-" + name, runnable);
            setDaemon(true);
        }
    }

    public static DaemonThread daemonThread(String name, Runnable runnable) {
        return new DaemonThread(name, runnable);
    }

    private Runnable runnable;

    public InnerThread(String name, Runnable runnable) {
        super(name);
        this.runnable = runnable;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                try {
                    runnable.run();
                }
                catch (IOException | NetworkLayerException e) {
                    LOGGER.warn(getName() + "发生错误", e);
                }
            }
        }
        catch (Throwable e) {
            LOGGER.error(getName() + "异常退出", e);
        }
    }
}
